// ==UserScript==
// @name         网站种子弹窗搜索
// @namespace    https://gitee.com/jetpack99/search-for
// @version      1.1.0
// @description  一款用于网站种子弹窗搜索的神器（优化版）
// @author       jetpack99
// @match        https://www.jphoo13.top/*
// @match        https://www.jphoo9.com/*
// @updateURL    https://gitee.com/jetpack99/search-for/blob/master/script.user.js
// @downloadURL  https://gitee.com/jetpack99/search-for/blob/master/script.user.js
// @icon         https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
// @grant        none
// ==/UserScript==


(function() {
    'use strict';

    const url ='cili.info';

    // 注入全局样式（增加加载动画样式）
    const style = document.createElement('style');
    style.textContent = `
        /* 列表项按钮样式 */
        .action-container {
            position: absolute;
            right: 8px;
            bottom: 17%;
            transform: translateY(-50%);
            display: flex;
            gap: 4px;
        }
        .action-button {
            padding: 2px 8px;
            background-color: #3b82f6;
            color: white;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            transition: background-color 0.3s;
            border: none;
        }
        .action-button:hover {
            background-color: #2563eb;
        }
        .action-button:disabled {
            background-color: #94a3b8;
            cursor: not-allowed;
        }

        /* 浮动窗口样式 */
        .floating-window {
            position: fixed;
            right: 20px;
            bottom: 80px;
            width: 350px;
            height: 90vh;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            display: flex;
            flex-direction: column;
            overflow: hidden;
            z-index: 9000;
            transform: scale(0.95);
            opacity: 0;
            transition: all 0.3s ease;
            visibility: hidden;
        }
        .floating-window.visible {
            transform: scale(1);
            opacity: 1;
            visibility: visible;
        }
        .floating-window.dragging {
            transition: none !important;
        }

        /* 窗口头部 */
        .window-header {
            padding: 8px 16px;
            background-color: #f3f4f6;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: move;
            user-select: none;
        }
        .window-title {
            font-weight: 500;
            color: #333;
        }
        .close-button {
            color: #6b7280;
            cursor: pointer;
            font-size: 18px;
        }
        .close-button:hover {
            color: #374151;
        }

        /* 内容区域与加载动画 */
        .window-content {
            flex: 1;
            overflow: hidden;
            position: relative; /* 用于加载动画定位 */
        }
        .search-iframe {
            width: 100%;
            height: 100%;
            border: 0;
            transition: opacity 0.3s ease;
        }
        .loading-indicator {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            display: none;
        }
        .loading-icon {
            color: #3b82f6;
            font-size: 32px;
            margin-bottom: 10px;
        }
        .loading-text {
            color: #64748b;
            font-size: 14px;
        }

        /* 更新按钮 */
        #updateButton {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 9000;
            padding: 10px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            transition: background-color 0.3s;
        }
        #updateButton:hover {
            background-color: #45a049;
        }
    `;
    document.head.appendChild(style);

    // 引入图标库
    const fontAwesome = document.createElement('link');
    fontAwesome.rel = 'stylesheet';
    fontAwesome.href = 'https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css';
    document.head.appendChild(fontAwesome);

    // 全局变量
    let floatingWindow = null;
    let isDragging = false;
    let startX = 0;
    let startY = 0;
    let initialTranslateX = 0;
    let initialTranslateY = 0;
    let searchDebounce = null; // 防抖定时器

    // 创建浮动窗口（包含加载动画容器）
    function createFloatingWindow() {
        if (floatingWindow) return;

        floatingWindow = document.createElement('div');
        floatingWindow.className = 'floating-window';
        floatingWindow.innerHTML = `
            <div class="window-header">
                <span class="window-title">搜索结果</span>
                <span class="close-button"><i class="fa fa-times"></i></span>
            </div>
            <div class="window-content">
                <!-- 加载动画 -->
                <div class="loading-indicator">
                    <div class="loading-icon"><i class="fa fa-spinner fa-spin"></i></div>
                    <div class="loading-text">搜索中...</div>
                </div>
                <!-- iframe容器（动态创建） -->
            </div>
        `;
        document.body.appendChild(floatingWindow);

        // 关闭按钮事件
        floatingWindow.querySelector('.close-button').addEventListener('click', () => {
            floatingWindow.classList.remove('visible');
        });

        // 绑定拖动事件
        bindDragEvents();
    }

    // 绑定拖动事件
    function bindDragEvents() {
        const header = floatingWindow.querySelector('.window-header');

        header.addEventListener('mousedown', (e) => {
            isDragging = true;
            floatingWindow.classList.add('dragging');

            startX = e.clientX;
            startY = e.clientY;

            const transform = window.getComputedStyle(floatingWindow).transform;
            const matrix = new DOMMatrix(transform);
            initialTranslateX = matrix.e;
            initialTranslateY = matrix.f;

            document.body.style.userSelect = 'none';
        });

        document.addEventListener('mousemove', (e) => {
            if (!isDragging) return;

            const deltaX = e.clientX - startX;
            const deltaY = e.clientY - startY;

            floatingWindow.style.transform = `translate(${initialTranslateX + deltaX}px, ${initialTranslateY + deltaY}px) scale(1)`;
        });

        document.addEventListener('mouseup', () => {
            if (!isDragging) return;

            isDragging = false;
            floatingWindow.classList.remove('dragging');
            document.body.style.userSelect = '';
        });
    }

    // 更新窗口内容（核心优化：每次重建iframe）
    function updateWindowContent(searchText) {
        createFloatingWindow();
        const contentContainer = floatingWindow.querySelector('.window-content');
        const loadingIndicator = contentContainer.querySelector('.loading-indicator');

        // 1. 显示加载动画，移除旧iframe
        loadingIndicator.style.display = 'block';
        const oldIframe = contentContainer.querySelector('.search-iframe');
        if (oldIframe) oldIframe.remove();

        // 2. 创建新iframe
        const newIframe = document.createElement('iframe');
        newIframe.className = 'search-iframe';
        newIframe.src = `https://${url}/search?q=${encodeURIComponent(searchText)}`;
        newIframe.style.opacity = '0'; // 初始透明

        // 3. 加载完成处理
        newIframe.onload = () => {
            loadingIndicator.style.display = 'none';
            newIframe.style.opacity = '1'; // 加载完成后显示
        };

        // 4. 加载失败处理
        newIframe.onerror = () => {
            loadingIndicator.innerHTML = `
                <div class="loading-icon"><i class="fa fa-exclamation-circle"></i></div>
                <div class="loading-text">加载失败，请重试</div>
            `;
        };

        // 5. 添加新iframe到容器
        contentContainer.appendChild(newIframe);

        // 6. 更新标题并显示窗口
        floatingWindow.querySelector('.window-title').textContent = `搜索: ${searchText}`;
        floatingWindow.classList.add('visible');
    }

    // 获取列表项并添加按钮（增加防抖）
    function getListItems() {
        const liElements = document.querySelectorAll('.q-col-gutter-md > div');
        liElements.forEach(li => {
            if (li.querySelector('.action-container')) return;

            const actionDiv = document.createElement('div');
            actionDiv.className = 'action-container';
            const button = document.createElement('button');
            button.className = 'action-button';
            button.textContent = '搜索';

            // 点击事件添加防抖（300ms）
            button.addEventListener('click', (e) => {
                e.stopPropagation();
                const nameElement = li.querySelector('.text-weight-bolder');
                const nameText = nameElement ? nameElement.textContent.trim() : '';
                if (!nameText) return;

                // 防抖处理：避免快速多次点击
                clearTimeout(searchDebounce);
                button.disabled = true; // 临时禁用按钮
                searchDebounce = setTimeout(() => {
                    updateWindowContent(nameText);
                    button.disabled = false; // 恢复按钮
                }, 300);
            });

            actionDiv.appendChild(button);
            li.appendChild(actionDiv);
            li.style.position = 'relative';
        });
    }

    // 创建更新按钮
    const updateButton = document.createElement('button');
    updateButton.id = 'updateButton';
    updateButton.textContent = '更新状态';
    updateButton.addEventListener('click', getListItems);
    document.body.appendChild(updateButton);

    // 延迟初始化 + 监听页面滚动加载（针对动态加载的列表）
    setTimeout(getListItems, 2000);
    // 监听滚动事件，对动态加载的内容也添加按钮
    window.addEventListener('scroll', () => {
        clearTimeout(searchDebounce);
        searchDebounce = setTimeout(getListItems, 500); // 滚动停止后执行
    });

})();